{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "import numpy as np\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "FLAGS = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的 MNIST 数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "<font style='color:red'>注意修改目录</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-1ef894c1e7f5>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /root/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /root/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /mnist/input_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /root/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /root/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /mnist/input_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /root/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将参数提出来方便调试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])                        #输入的数据占位符\n",
    "y_actual = tf.placeholder(tf.float32, shape=[None, 10])            #输出的标签占位符\n",
    "keep_prob = tf.placeholder(\"float\")\n",
    "x_image = tf.reshape(x, [-1, 28, 28, 1])                           # 转换输入数据shape,以便于用于网络中\n",
    "lr = tf.Variable(0.1, dtype=tf.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义一个函数，用于初始化所有的权值 W\n",
    "def w_variable(shape):\n",
    "    return tf.Variable(tf.truncated_normal(shape, stddev=0.1))\n",
    "\n",
    "# 定义一个函数，用于初始化所有的偏置项 b\n",
    "def b_variable(shape):\n",
    "    return tf.Variable(tf.constant(0.1, shape=shape))\n",
    " \n",
    "# 定义一个函数，用于构建卷积层\n",
    "def conv2d(x, W):\n",
    "    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n",
    "\n",
    "# 定义一个函数，用于构建池化层\n",
    "def max_pool(x):\n",
    "    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#构建网络\n",
    "W_conv1 = w_variable([5,5,1,32])\n",
    "b_conv1 = b_variable([32])\n",
    "h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # 第一个卷积层\n",
    "#h_conv1 = tf.nn.sigmoid(conv2d(x_image, W_conv1) + b_conv1)  # 第一个卷积层\n",
    "#h_conv1 = tf.nn.tanh(conv2d(x_image, W_conv1) + b_conv1)  # 第一个卷积层\n",
    "h_pool1 = max_pool(h_conv1)  # 第一个池化层\n",
    "\n",
    "W_conv2 = w_variable([5, 5, 32, 64])\n",
    "b_conv2 = b_variable([64])\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  # 第二个卷积层\n",
    "#h_conv2 = tf.nn.sigmoid(conv2d(h_pool1, W_conv2) + b_conv2)  # 第二个卷积层\n",
    "#h_conv2 = tf.nn.tanh(conv2d(h_pool1, W_conv2) + b_conv2)  # 第二个卷积层\n",
    "h_pool2 = max_pool(h_conv2)  # 第二个池化层\n",
    "\n",
    "W_fc1 = w_variable([7 * 7 * 64, 1024])\n",
    "b_fc1 = b_variable([1024])\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])  # reshape成向量\n",
    "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  # 第一个全连接层\n",
    "h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  # dropout层\n",
    "\n",
    "W_fc2 = w_variable([1024, 10])\n",
    "b_fc2 = b_variable([10])\n",
    "y_predict = tf.matmul(h_fc1_drop, W_fc2) + b_fc2  # 无需softmax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算损失和(交叉熵+正则),只计算神经网络边上权重的正则化损失\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_actual, logits=y_predict))\n",
    " \n",
    "#train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)  # 梯度下降法\n",
    "train_step = tf.train.GradientDescentOptimizer(lr).minimize(cross_entropy)  # 梯度下降法\n",
    "\n",
    "\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))  # 精确度计算\n",
    "\n",
    "init_op = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 1000, entropy loss: 0.094091\n",
      "训练集准确率: 0.98 测试集准确率 0.9747\n",
      "step 2000, entropy loss: 0.029512\n",
      "训练集准确率: 0.97 测试集准确率 0.9832\n",
      "step 3000, entropy loss: 0.050954\n",
      "训练集准确率: 0.99 测试集准确率 0.9825\n",
      "step 4000, entropy loss: 0.097339\n",
      "训练集准确率: 0.99 测试集准确率 0.985\n",
      "step 5000, entropy loss: 0.028496\n",
      "训练集准确率: 0.99 测试集准确率 0.9865\n",
      "step 6000, entropy loss: 0.005672\n",
      "训练集准确率: 1.0 测试集准确率 0.9879\n",
      "step 7000, entropy loss: 0.014014\n",
      "训练集准确率: 1.0 测试集准确率 0.9879\n",
      "step 8000, entropy loss: 0.007014\n",
      "训练集准确率: 1.0 测试集准确率 0.989\n",
      "step 9000, entropy loss: 0.010506\n",
      "训练集准确率: 0.99 测试集准确率 0.9868\n",
      "step 10000, entropy loss: 0.011640\n",
      "训练集准确率: 0.99 测试集准确率 0.9893\n"
     ]
    }
   ],
   "source": [
    "sess = tf.Session()\n",
    "sess.run(init_op)\n",
    "for step in range(10000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    _, loss = sess.run( [train_step, cross_entropy], feed_dict={x: batch_xs, y_actual: batch_ys, keep_prob:0.5})\n",
    "\n",
    "    if (step+1) % 1000 == 0:\n",
    "        print('step %d, entropy loss: %f' %  (step+1, loss))\n",
    "        train_acc =  sess.run(accuracy, feed_dict={x: batch_xs, y_actual: batch_ys, keep_prob:0.5})\n",
    "        test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images,y_actual: mnist.test.labels, keep_prob:0.5})\n",
    "        print('训练集准确率:',train_acc,'测试集准确率',test_acc)         "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
